<?php
/**
 * CDN上报片源媒体注入进度处理类
 * User: kan.yang@starcor.cn
 * Date: 18-01-27
 * Time: 上午11:40
 */

set_time_limit(0);error_reporting(0);
header('Content-Type:text/xml; charset=utf-8');
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
//加载 xml转为数组的np库
\ns_core\m_load::load_np("np_xml_to_array.class.php");
\ns_core\m_load::load_np("np_xml2array.class.php");

class notify
{
    //数据库/缓存处理类
    private $obj_dc = null;
    //SP ID
    private $str_sp_id = 'coship';
    //CDN上报XML
    private $str_xml_content = '';

    /**
     * 默认构造函数
     */
    public function __construct($str_xml)
    {
        $this->obj_dc = m_config::get_dc();
        $this->str_xml_content = $str_xml;
    }

    /**
     * 处理CDN上报信息入口
     */
    public function init()
    {
        $bool_ret = false;
        //处理CDN反馈的信息
        $str_content = m_config::trim_xml_header($this->str_xml_content);
        if(m_config::is_xml($str_content))
        {
            $dom = new DOMDocument('1.0', 'utf-8');
            $dom->loadXML($str_content);
            $xml = $dom->saveXML();
            //转化XML为数组格式
            $xml_arr = np_xml2array::getArrayData($xml);
            if(is_array($xml_arr) && !empty($xml_arr) && !empty($xml_arr['data']))
            {
                //处理CDN上报信息核心函数
                $bool_ret = $this->_handler_feedback_content($xml_arr['data']);
            }
        }

        return $bool_ret;
    }

    /**
     * 处理CDN上报信息核心函数
     * @param $arr_content
     * @return bool true成功；false失败
     */
    private function _handler_feedback_content($arr_content)
    {
        //验证参数有效性
        $str_asset_id = isset($arr_content['attributes']['assetID']) ? $arr_content['attributes']['assetID'] : '';
        $str_provider_id = isset($arr_content['attributes']['providerID']) ? $arr_content['attributes']['providerID'] : '';
        $str_content_type= isset($arr_content['attributes']['contentType']) ? $arr_content['attributes']['contentType'] : '';
        $str_volume_name = isset($arr_content['attributes']['volumeName']) ? $arr_content['attributes']['volumeName'] : '';
        if(empty($str_asset_id) || empty($str_provider_id) || empty($str_content_type) || empty($str_volume_name))
        {
            return false;
        }
        //根据媒资ID 查询SP信息
        $str_sql  = "select s.*,m.nns_cp_id ";
        $str_sql .= "from nns_mgtvbk_sp s LEFT JOIN nns_vod_media m ON LOCATE(CONCAT(',', m.`nns_cp_id`, ','),s.`nns_bind_cp`) > 0 ";
        $str_sql .= "where s.nns_state = 0 and m.nns_id = '{$str_asset_id}'";
        $arr_sp_info = nl_db_get_one($str_sql,$this->obj_dc->db());
        if(!is_array($arr_sp_info) || empty($arr_sp_info) || empty($arr_sp_info['nns_config']))
        {
            m_config::base_write_log('message','request',date('Y-m-d H:i:s') . ' 根据片源媒资ID查询 SP信息失败。SQL：' .addslashes($str_sql));
            return false;
        }
        //获取CDN播放串公共域名地址
        $str_sp_config = json_decode($arr_sp_info['nns_config']);
        $str_play_url_ip = is_object($str_sp_config) ? $str_sp_config->c2_play_url_ip : $str_sp_config['c2_play_url_ip'];
        unset($str_sp_config); unset($arr_sp_info);
        //子节点
        if(is_array($arr_content['children']) && !empty($arr_content['children']))
        {
            $bool_state = false; $bool_modify_ret = true; $str_play_url = ''; $str_modify_sql = '';
            foreach($arr_content['children'] as $children)
            {
                //上报状态
                $bool_state = isset($children['attributes']['state']) && strtolower($children['attributes']['state']) == 'complete' ? 0 : '-1';
                $str_bit_rate = isset($children['attributes']['transferBitRate']) && strlen($children['attributes']['transferBitRate']) > 0 ? $children['attributes']['transferBitRate'] : '';
                //更新片源媒资的播放串地址
                if(empty($bool_state) && !empty($str_play_url_ip))
                {
                    $str_play_url = json_encode(array(
                        'play_url' => $str_play_url_ip . '/' . strtolower($str_content_type) . '/' . $str_provider_id . '_' . $str_asset_id . '_' . $str_bit_rate . '.m3u8?sessionId=' . $str_asset_id
                    ));
                    $str_modify_sql = 'update nns_vod_media set nns_ext_url = \'' . addslashes($str_play_url) . '\' where nns_id = \'' . $str_asset_id . '\' and nns_kbps = \'' . $str_bit_rate . '\'';
                    $bool_modify_ret = nl_query_by_db($str_modify_sql,$this->obj_dc->db());
                    m_config::base_write_log('message','request',date('Y-m-d H:i:s') . ' 片源【' . $str_asset_id . '】媒体内容注入CDN成功，更新播放串地址' . ($bool_modify_ret ? '成功' : '失败') . '。SQL：' . addslashes($str_modify_sql));
                }
                else
                {
                    m_config::base_write_log('message','request',date('Y-m-d H:i:s') . ' 片源【' . $str_asset_id . '】媒体内容注入CDN失败');
                }
                //更新注入CDN注入队列状态
                $str_where = 'nns_type = \'media\' and nns_ref_id = \'' . $str_asset_id . '\'';
                $str_modify_sql = 'update nns_mgtvbk_c2_task set nns_status = ' . $bool_state . ' where ' . $str_where;
                nl_query_by_db($str_modify_sql,$this->obj_dc->db());
                //更新CDN日志状态
                $str_modify_sql = 'update nns_mgtvbk_c2_log set nns_notify_result = ' . $bool_state . ' where lower(nns_task_type) = \'movie\' and nns_task_id in (select nns_id from nns_mgtvbk_c2_task where ' . $str_where . ')';
                nl_query_by_db($str_modify_sql,$this->obj_dc->db());
                //更新点播片源转码新老路径关系表（广州孝乐专区）
                $str_modify_sql = 'update nns_ls_media_path_relation set nns_state = ' . (empty($bool_state) ? 1 : 2) . ' where nns_id = \'' . $str_asset_id . '\'';
                nl_query_by_db($str_modify_sql,$this->obj_dc->db());
                $str_play_url = '';
            }
            unset($bool_state); unset($str_play_url); unset($str_modify_sql);
        }
        return true;
    }
}

//获取客户端数据流
$str_xml_content = file_get_contents("php://input");
m_config::base_write_log('message','request',date('Y-m-d H:i:s') . ' 片源媒体内容注入CDN反馈信息：' . addslashes($str_xml_content));
//处理CDN上报内容
$obj_notify = new notify($str_xml_content);
$obj_notify->init();
//释放资源
unset($str_xml_content); unset($obj_notify);

